/**
 * 读取插件配置
 * 只有在项目启动才执行一次
 * 插件安装、更新、请用接口调用
 */
var _ljs=require("./mmlog").root("[sever/pluginManager.js]");

var fs = require("fs");

var util = require("./util");

var Plugins = [];

function Plugin(package) {
	for (var a in package) {
		this[a] = package[a];
	}
	this.uuid = util.sha1(package.name+package.version+package.main);
	this.module = "myPlu/" + package.main;
}

function loadPlugin(callback) {

	var root = "./client/plugins";

	fs.readdir(root, function(error, files) {
		if (!error) {
			for (a in files) {
				if (files[a].indexOf(".") == -1) {
					var data = fs.readFileSync(root + "/" + files[a] + "/package.json", "utf-8");
					Plugins.push(new Plugin(JSON.parse(data)));
				}
			}
			callback && callback(Plugins);
			_ljs.info("读取插件配置:\n",Plugins);
		}else{
			_ljs.error("读取插件配置失败:\n",error);
			callback && callback(-1);
		}
	})

}


module.exports = {
	
	/**
	 * 插件模块初始化函数
	 * 用于参数传递、初始化信息
	 * @param {Object} _app
	 */
	init:function(callback){
		loadPlugin(callback);
	},
	
	/**
	 * 加载插件配置信息
	 */
	load: function() {
		return Plugins;
	},
	
	/**
	 * 重新加载插件信息
	 * 异步都读取
	 * @param {Object} callback
	 */
	reload:function(callback){
		_ljs.debug("重新加载插件")
		loadPlugin(callback);
	}
}